﻿package {

	import flash.net.URLLoader;
	import flash.net.URLRequest;
	import flash.events.Event;
	
	public class LinkLoader {
		
		private var xmlPath:String;
		private var xmlFile:XML;
		private var xmlLoadComplete:Boolean = false;
		private var loader:URLLoader;
		
		private var numberOfItems:uint = 0;
		private var itemDescriptions:Vector.<String>;
		private var itemURLs:Vector.<String>;
		
		private var parentObj:Object3D;
		
		public function LinkLoader(xmlPath:String, parentObj:Object3D) {
			this.parentObj = parentObj;
			
			this.xmlPath = xmlPath;
			
			// Load the file, call xmlLoaded on completion
			loader = new URLLoader();
			
			loader.load(new URLRequest(xmlPath));
			loader.addEventListener(Event.COMPLETE, xmlLoaded);
			
		}
		
		public function xmlLoaded(e:Event):void {
			
			if ((e.target as URLLoader) != null ) {
				
				xmlFile = new XML(loader.data);
				numberOfItems = xmlFile.items.item.length();
				
				itemDescriptions = new Vector.<String>;
				itemURLs = new Vector.<String>;
				
				// Store the link description and link URLs
				for(var i:int = 0; i < numberOfItems; i++) {
					itemDescriptions[i] = xmlFile.items.item[i].label;
					itemURLs[i] = xmlFile.items.item[i].linkTo;
				}
				
			}
			
			xmlLoadComplete = true;
			parentObj.createMenuItems();
		}
		
		public function areLinksLoaded():Boolean {
			return xmlLoadComplete;
		}
		
		public function getNumberOfItems():uint {
			return numberOfItems;
		}
		
		public function getItemDescriptionAtIndex(index:uint):String {
			if(index < numberOfItems) {
				return itemDescriptions[index];
			}
			return "";
		}
		
		public function getItemURLAtIndex(index:uint):String {
			if(index < numberOfItems) {
				return itemURLs[index];
			}
			return "";
		}
		
	}
	
}